﻿using AutoMapper;
using MediatR;
using ProductManagement.Applcation.Command;
using ProductManagement.Domain.ProductsDomain;
using ProductManagement.Infrstructre.Interface;

namespace ProductManagement.Applcation.CommandHanlers
{
    /// <summary>
    /// 产品添加中介者
    /// </summary>
    public class ProductCreateCommandHandler:IRequestHandler<ProductCreateCommand,int>
    {
        private readonly InterfaceProductRepository productRepository;
        private readonly IMapper mapper;

        public ProductCreateCommandHandler(InterfaceProductRepository productRepository, IMapper mapper)
        {
            this.productRepository = productRepository;
            this.mapper = mapper;
        }

        public async Task<int> Handle(ProductCreateCommand request, CancellationToken cancellationToken)
        {
            var name = (await productRepository.GetAll()).Where(x => x.PName == request.dto.PName).Count();
            if (name > 0)
            {
                return -1;
            }
            else
            {
                return await productRepository.AddAsync(mapper.Map<Product>(request.dto));
            }
        }
    }
}
